﻿using System.Text.Json;

namespace EssentialWebFramework.Utils
{
    /// <summary>
    /// JSON 实用工具类
    /// </summary>
    public class JsonUtils
    {
        /// <summary>
        /// JSON 序列化选项（用于与前端交互）
        /// </summary>
        public static JsonSerializerOptions FrontJsonSerializerOptions = new JsonSerializerOptions
        {
            PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
            Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
            WriteIndented = true,
        };

        /// <summary>
        /// 序列化（用于与前端交互）
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string JsonSerializeForFront<T>(T obj)
        {
            return JsonSerializer.Serialize(obj, FrontJsonSerializerOptions);
        }

        /// <summary>
        /// 反序列化（用于与前端交互）
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static T JsonDeserializeForFront<T>(string json)
        {
            return JsonSerializer.Deserialize<T>(json, FrontJsonSerializerOptions);
        }

        /// <summary>
        /// JSON 序列化选项（用于缓存）
        /// </summary>
        public static JsonSerializerOptions CacheJsonSerializerOptions = new JsonSerializerOptions
        {
            Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
            WriteIndented = true,
        };

        /// <summary>
        /// 序列化（用于缓存）
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string JsonSerializeForCache<T>(T obj)
        {
            return JsonSerializer.Serialize(obj, CacheJsonSerializerOptions);
        }

        /// <summary>
        /// 反序列化（用于缓存）
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static T JsonDeserializeForCache<T>(string json)
        {
            return JsonSerializer.Deserialize<T>(json, CacheJsonSerializerOptions);
        }
    }
}
